import cv2
import pytesseract
import numpy as np
import os

pytesseract.pytesseract.tesseract_cmd = r'H:\Tesseract-OCR\tesseract.exe'  # 注意：使用 raw string (r'') 或
# --- 配置 ---
# 如果Tesseract不在系统PATH中，需要指定其路径 (Windows常见)
# pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'

# 图像路径
image_path = 'H:\\py\\image.png'  # 替换为你的图片路径

# 指定要识别的区域坐标 (x, y, width, height)
# x, y 是左上角坐标
# width, height 是区域的宽和高
roi_x, roi_y, roi_width, roi_height = 1680, 335, 50, 23  # 示例坐标
roi_x1, roi_y1, roi_width1, roi_height1 = 1810, 438, 50, 23  # 示例坐标

# --- 步骤 1: 加载图像 ---
image = cv2.imread(image_path)
if image is None:
    raise FileNotFoundError(f"无法加载图像: {image_path}")

# --- 步骤 2: 提取指定区域 (ROI) ---
roi = image[roi_y:roi_y + roi_height, roi_x:roi_x + roi_width]
roi1 = image[roi_y1:(roi_y1 + roi_height1), roi_x1:(roi_x1 + roi_width1)]

# --- 步骤 3: (可选) 对ROI进行预处理以提高OCR准确性 ---
# 转换为灰度图
gray_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
gray_roi1 = cv2.cvtColor(roi1, cv2.COLOR_BGR2GRAY)

# 二值化 (可选，根据图像质量调整)
# _, binary_roi = cv2.threshold(gray_roi, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# 或者使用自适应阈值
# binary_roi = cv2.adaptiveThreshold(gray_roi, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)

# 去噪 (可选)
# denoised_roi = cv2.medianBlur(gray_roi, 3)

# 放大图像 (可选，有时对小字体有帮助)
# scale_factor = 2
# enlarged_roi = cv2.resize(denoised_roi, None, fx=scale_factor, fy=scale_factor, interpolation=cv2.INTER_CUBIC)

# 在这个例子中，我们使用灰度图
preprocessed_roi = gray_roi
preprocessed_roi1 = gray_roi1

# --- 步骤 4: 使用Tesseract进行OCR识别 ---
# 可以设置OCR配置参数
# 例如: '--psm 6' (假设为单个均匀文本块), '--oem 3' (使用LSTM OCR引擎)
# 'lang' 参数指定语言，例如 'chi_sim' (简体中文), 'eng' (英文), 'chi_sim+eng' (中英文)
config = '--psm 6 --oem 3 -l eng'  # 根据需求调整
# config = '--psm 6 --oem 3 -l chi_sim+eng'  # 识别中英文

text = pytesseract.image_to_string(preprocessed_roi, config=config)
text1 = pytesseract.image_to_string(preprocessed_roi1, config=config)

# 清理结果 (去除换行符、多余空格等)
recognized_text = text.strip()
recognized_text1 = text1.strip()

# --- 步骤 5: 输出结果 ---
print(f"在区域 ({roi_x}, {roi_y}, {roi_width}, {roi_height}) 内识别到的文本:")
print(recognized_text)

print(f"在区域 ({roi_x1}, {roi_y1}, {roi_width1}, {roi_height1}) 内识别到的文本:")
print(recognized_text1)

# --- (可选) 可视化 ---
# 在原图上绘制ROI区域
cv2.rectangle(image, (roi_x, roi_y), (roi_x + roi_width, roi_y + roi_height), (0, 255, 0), 2)
cv2.putText(image, "ROI", (roi_x, roi_y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)


# 在原图上绘制ROI区域
cv2.rectangle(image, (roi_x1, roi_y1), (roi_x1 + roi_width1, roi_y1 + roi_height1), (0, 255, 0), 2)
cv2.putText(image, "ROI", (roi_x1, roi_y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)


# 显示原图和ROI
#cv2.imshow('Original Image with ROI', image)
#cv2.imshow('Extracted ROI', preprocessed_roi)
#cv2.imshow('Extracted ROI1', preprocessed_roi1)

cv2.waitKey(0)
cv2.destroyAllWindows()

save_dir = r'H:\py\image'
if not os.path.exists(save_dir):
    os.makedirs(save_dir)
# --- (可选) 保存处理后的图像 ---
cv2.imwrite('H:\\py\\image\\output_with_roi.jpg', image)
cv2.imwrite('H:\\py\\image\\extracted_roi.jpg', preprocessed_roi)
cv2.imwrite('H:\\py\\image\\extracted_roi1.jpg', preprocessed_roi1)

